﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace Icoders.MarketTracker.Web.Lib.Security
{
    public class CustomAuthorize :AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var roles = Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (roles.Contains("ROLE_FSRUSER", StringComparer.OrdinalIgnoreCase))
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    area="mobile",
                    controller = "maccount",
                    action = "Login",
                    returnUrl = filterContext.HttpContext.Request.RawUrl
                }));
            }
            else 
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    area="",
                    controller = "account",
                    action = "login",
                    returnUrl = filterContext.HttpContext.Request.RawUrl
                }));
            }
           

        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            
            if (filterContext.HttpContext.User.Identity is CustomIdentity )
            {
                CustomIdentity user = (CustomIdentity)filterContext.HttpContext.User.Identity;
                var roles = Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (roles.Contains("ROLE_FSRUSER", StringComparer.OrdinalIgnoreCase) && !user.HasChangedPassword)
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        area = "mobile",
                        controller = "maccount",
                        action = "changepassword",
                        returnUrl = filterContext.HttpContext.Request.RawUrl
                    }));
                }
                else if(!user.HasChangedPassword)
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        area = "",
                        controller = "account",
                        action = "changepassword",
                        returnUrl = filterContext.HttpContext.Request.RawUrl
                    }));
                }
            }
            base.OnAuthorization(filterContext);
        }

    }
}
